package com.varton.executor.impl;

import com.varton.executor.Executor;
import com.varton.po.Company;

import java.sql.*;

public class SimpleExecutor implements Executor{
    public <T> T execute(String statment, Object[] prama) {
        Connection connection = this.getConnection();
        Company company = null;
        try {
            Statement prepareStatement = connection.prepareStatement(statment);
            String sql = statment.replace("?",String.valueOf(prama[0]));
            System.out.println(sql);
            ResultSet res = prepareStatement.executeQuery(sql);
            company = new Company();
            while (res.next()){
                company.setId(res.getLong(1));
                company.setName(res.getString(2));
            }
            res.close();
            prepareStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            connection.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return (T) company;
    }

    private Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/charge-pay?characterEncoding=UTF-8&useSSL=false","root","root");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
}
